package com.liu.nb.util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "userinfo.jwt")
public class JwtUtils {
    private long expire;
    private String privateKey;
    private String header;
//    生成jwt
    public String generateToken(String username){
        Date nowDate=new Date();
        Date expireDate=new Date(nowDate.getTime()+ 1000 * expire);
     return Jwts.builder()
                .setHeaderParam("type","JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)//创建时间
                .setExpiration(expireDate)//过期时间
                .signWith(SignatureAlgorithm.HS512,privateKey)
                .compact();
    }
//    解析jwt
    public Claims getClaims(String jwt){
        try {
           return Jwts.parser()
                    .setSigningKey(privateKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
           return null;
        }
    }
//    jwt是否过期
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
